package de.medizin.uni.halle.irm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class DESEncryption {
	
	public static void encrypt(File sd, FileInputStream fis){
		try {
			String key = "bornborn"; // needs to be at least 8 characters for DES
			//FileInputStream fis = new FileInputStream("original.txt");
			//FileOutputStream fos = new FileOutputStream("bornbackup2");
            String backupDBPath = "bornbackup";
            File backupDB = new File(sd, backupDBPath);
            FileOutputStream fos =  new FileOutputStream(backupDB);
			encrypt(key, fis, fos);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	public static void decrypt(File sd){
		try {
			String key = "bornborn"; // needs to be at least 8 characters for DES
	        String backupDBPath = "bornbackup";
	        File backupDB = new File(sd, backupDBPath);
			FileInputStream fis2 = new FileInputStream(backupDB);
	        String backupDBPath2 = "bornrestore";
	        File backupDB2 = new File(sd, backupDBPath2);
			FileOutputStream fos2 = new FileOutputStream(backupDB2);
			decrypt(key, fis2, fos2);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
	
	public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
		encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
	}

	public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
		encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
	}

	public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {

		try{
			DESKeySpec dks = new DESKeySpec(key.getBytes());
			SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
			SecretKey desKey = skf.generateSecret(dks);
			Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE
	
			if (mode == Cipher.ENCRYPT_MODE) {
				cipher.init(Cipher.ENCRYPT_MODE, desKey);
				CipherInputStream cis = new CipherInputStream(is, cipher);
				doCopy(cis, os);
			} else if (mode == Cipher.DECRYPT_MODE) {
				cipher.init(Cipher.DECRYPT_MODE, desKey);
				CipherOutputStream cos = new CipherOutputStream(os, cipher);
				doCopy(is, cos);
			}
		} catch(Exception E) {
			E.printStackTrace();
		}
	}

	public static void doCopy(InputStream is, OutputStream os) throws IOException {
		byte[] bytes = new byte[64];
		int numBytes;
		while ((numBytes = is.read(bytes)) != -1) {
			os.write(bytes, 0, numBytes);
		}
		os.flush();
		os.close();
		is.close();
	}

}